/*
 * @Author: shuai
 * @Date: 2021-03-31 11:31:53
 * @LastEditors: shuai
 * @LastEditTime: 2021-03-31 14:06:02
 * @Description: file content
 */
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

import { ActionContext } from 'vuex'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
  }
}

const state = getDefaultState()

export type State = typeof state

const mutations = {
  RESET_STATE: (state: State) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state: State, token: string) => {
    state.token = token
  },
  SET_NAME: (state: State, name: string) => {
    state.name = name
  },
  SET_AVATAR: (state: State, avatar: string) => {
    state.avatar = avatar
  },
}

const actions = {
  // user login
  login({ commit }: ActionContext<State, unknown>, userInfo: { username: string; password: string }) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response: { data: { token: string } }) => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve('')
        })
        .catch((error: Error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }: ActionContext<State, unknown>) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response: { data: { name: string; avatar: string } }) => {
          const { data } = response

          if (!data) return reject('Verification failed, please Login again.')

          const { name, avatar } = data

          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          resolve(data)
        })
        .catch((error: Error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }: ActionContext<State, unknown>) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve('')
        })
        .catch((error: Error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }: ActionContext<State, unknown>) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve('')
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
